<template>
  <div>
    <!-- 上面:三级联动 -->
    <el-card>
      <Category @getCategoryId="getCategoryId" :scene="scene"></Category>
    </el-card>
    <!-- 展示平台属性的表格 -->
    <el-card style="margin: 10px 0px">
      <!-- 属性列表的地方 -->
      <div v-show="scene == 0">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!category3Id"
          @click="changeScene"
          >添加属性</el-button
        >
        <el-table style="width: 100%; margin: 10px 0px" border :data="attrList">
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="attrName"
            label="属性名称"
            width="180"
          ></el-table-column>
          <el-table-column prop="prop" label="属性值列表" width="width">
            <!-- row:就是attrList数组里面元素【对象】 row每一个平台属性对象-->
            <template slot-scope="{ row, $index }">
              <el-tag
                type="success"
                v-for="(attrValue, index) in row.attrValueList"
                :key="attrValue.id"
                style="margin: 2px 5px"
                >{{ attrValue.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="180">
            <template slot-scope="{ row, $index }">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="mini"
                title="修改"
                @click="updateAttr(row)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                title="删除"
                @click="deleteAttr(row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <el-form :inline="true" ref="form" :model="attrForm">
          <el-form-item label="属性名">
            <el-input v-model="attrForm.attrName"></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addAttr"
          :disabled="!attrForm.attrName"
          >添加属性值</el-button
        >
        <el-button @click="scene = 0">取消</el-button>
        <el-table
          style="width: 100%; margin: 20px 0px"
          border
          :data="attrForm.attrValueList"
        >
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column prop="prop" label="属性值名称">
            <template slot-scope="{ row, $index }">
              <el-input
                size="mini"
                v-model="row.valueName"
                v-if="row.show"
                @blur="toLook(row)"
                @keyup.native.enter="toLook(row)"
                :ref="$index"
              ></el-input>
              <span v-else @click="toEdit(row, $index)" style="display: block"
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作">
            <template slot-scope="{row,$index}">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="attrForm.attrValueList.splice($index,1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="save" :disabled="!attrForm.attrValueList.length">保存</el-button>
        <el-button @click="scene = 0">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
//按需引入
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "Attr",
  data() {
    return {
      category1Id: "",
      category2Id: "",
      category3Id: "",
      //属性列表
      attrList: [],
      //属性,控制显示属性列表|显示添加或者修改列表
      scene: 0,
      attrForm: {
        attrName: "", //属性名字
        //收集相应属性的属性值
        attrValueList: [],
        categoryId: "", //三级分类的id
        categoryLevel: 3, //告诉服务器三级id
      },
    };
  },
  methods: {
    //获取儿子给父亲传递过来数据回调
    getCategoryId({ categoryId, flag }) {
      switch (flag) {
        case 1:
          this.category1Id = categoryId;
          //父组件每一次接受儿子给的一级分类的id，要把上一次的二级、三级分类的id清除
          this.category2Id = "";
          this.category3Id = "";
          break;
        case 2:
          //父组件每一次接受儿子给的二级分类的id，要把上一次的三级分类的id清除
          this.category2Id = categoryId;
          this.category3Id = "";
          break;
        case 3:
          this.category3Id = categoryId;

          //获取属性值列表方法
          this.getAttrList();
          break;
      }
    },
    //获取属性列表的方法
    async getAttrList() {
      //相应的参数
      const { category1Id, category2Id, category3Id } = this;
      try {
        let result = await this.$API.attr.reqAttrList(
          category1Id,
          category2Id,
          category3Id
        );
        //保存数据
        this.attrList = result.data;
      } catch (error) {}
    },
    //添加属性按钮的回调
    changeScene() {
      this.scene = 1;

      //清空数据【防止用户在添加属性的时候，点击取消按钮】
      this.attrForm = {
        attrName: "", //属性名字
        //收集相应属性的属性值
        attrValueList: [],
        categoryId: this.category3Id, //三级分类的id
        categoryLevel: 3, //告诉服务器三级id
      };
    },
    //添加属性按钮的回调
    addAttr() {
      //点击添加属性的按钮，添加相应的属性值
      this.attrForm.attrValueList.push({
        attrId: this.attrForm.id, //属性的id
        valueName: "", //属性值名称
        show: true, //每一个属性值控制input与span切换
      });
      //新增的属性值聚焦
      this.$nextTick(() => {
        this.$refs[this.attrForm.attrValueList.length - 1].focus();
      });
    },
    //修改属性按钮的回调
    updateAttr(row) {
      //切换场景
      this.scene = 1;
      //展示已有的属性与属性值
      this.attrForm = cloneDeep(row);
      //由于已有的属性值没有show的字段，因此没办法实现模式切换
      //动态的给每一个属性值添加show属性
      this.attrForm.attrValueList.forEach((item) => {
        //$set:可以实现动态新增响应式属性【数据变化视图跟这变换】
        this.$set(item, "show", false);
      });

      //数组的替换：Vue检测到
      // this.attrForm.attrValueList = this.attrForm.attrValueList.map(item=>{
      //     return {
      //       ...item,
      //       show:false
      //     }
      // })
    },
    //查看模式
    toLook(row) {
      //第一种特殊情况:放置属性值为空
      if (row.valueName.trim() == "") {
        //提示信息
        this.$message({ type: "warning", message: "请你输入正确属性值名称" });
        return;
      }
      //some
      let repeat = this.attrForm.attrValueList.some((item) => {
        //需要把用户正在操作的属性值摘出去，与剩下的属性值名字进行对比
        if (row != item) {
          return item.valueName == row.valueName;
        }
      });
      //如果重复不变为查看模式
      if (repeat) {
        return;
      }
      row.show = false;
    },
    //编辑模式
    toEdit(row, $index) {
      //当点击span的时候，需要获取input，让它聚焦！！！！
      row.show = true;
      //获取input聚焦
      //第一种延迟器
      //第二种$nextTick
      this.$nextTick(() => {
        //nextTick：可以确保DOM结构加载完毕，能获取input，可以实现聚焦！！！
        this.$refs[$index].focus();
      });
    },
    //添加属性|修改属性的保存的操作->发请求
    async save() {
      //整理参数
      //注意事情:带给服务器的参数中，属性值空的不用给服务器带过去
      //注释事情:带给服务器的参数中，属性值不为空的，但是需要把show干掉
      this.attrForm.attrValueList = this.attrForm.attrValueList.filter(
        (item) => {
          if (item.valueName != "") {
            //属性值有东西
            delete item.show;
            return true;
          }
        }
      );

     //发请求
     try {
      await this.$API.attr.reqAddOrUpdateAttr(this.attrForm);
      //提示
      this.$message({type:'success',message:'保存成功'});
      //切换场景
      this.scene = 0;
      //在获取最新的相应属性列表数据
      this.getAttrList();
     } catch (error) {
       
     }

    },
    //删除平台属性
    async deleteAttr(row){
      try{
         await this.$API.attr.reqDeleteAttr(row.id);
         this.$message({type:'warning',message:'删除成功'})
         this.getAttrList()
      }catch(error){

      }
    }
  },
};
</script>
<style scoped></style>
